(function () {
    'use strict';

    /******************************************************************************
    Copyright (c) Microsoft Corporation.

    Permission to use, copy, modify, and/or distribute this software for any
    purpose with or without fee is hereby granted.

    THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
    REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
    AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
    INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
    LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
    OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
    PERFORMANCE OF THIS SOFTWARE.
    ***************************************************************************** */
    /* global Reflect, Promise, SuppressedError, Symbol, Iterator */


    function __awaiter(thisArg, _arguments, P, generator) {
        function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
        return new (P || (P = Promise))(function (resolve, reject) {
            function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
            function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
            function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
            step((generator = generator.apply(thisArg, _arguments || [])).next());
        });
    }

    function __generator(thisArg, body) {
        var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
        return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
        function verb(n) { return function (v) { return step([n, v]); }; }
        function step(op) {
            if (f) throw new TypeError("Generator is already executing.");
            while (g && (g = 0, op[0] && (_ = 0)), _) try {
                if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
                if (y = 0, t) op = [op[0] & 2, t.value];
                switch (op[0]) {
                    case 0: case 1: t = op; break;
                    case 4: _.label++; return { value: op[1], done: false };
                    case 5: _.label++; y = op[1]; op = [0]; continue;
                    case 7: op = _.ops.pop(); _.trys.pop(); continue;
                    default:
                        if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                        if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                        if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                        if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                        if (t[2]) _.ops.pop();
                        _.trys.pop(); continue;
                }
                op = body.call(thisArg, _);
            } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
            if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
        }
    }

    typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
        var e = new Error(message);
        return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
    };

    /**
     * NOTE 定义需要用到的api
     * 从[Savor](https://github.com/royc01/notion-theme/blob/main/theme.js)抄的
     * 来自[思源api文档](https://github.com/siyuan-note/siyuan/blob/master/API_zh_CN.md)
     * TODO 完成所需的所有api写入
     */
    /**
     * 向思源请求数据
     * @param url 请求url
     * @param data 请求数据(json encode)
     * @returns Promise\<any\>?
     */
    function _rqFORSiyuan(url, data) {
        return __awaiter(this, void 0, void 0, function () {
            var response;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, fetch(url, {
                            body: JSON.stringify(data),
                            method: 'POST',
                            headers: {
                                Authorization: "Token ''"
                            }
                        })];
                    case 1:
                        response = _a.sent();
                        if (!(response.status === 200)) return [3 /*break*/, 3];
                        return [4 /*yield*/, response.json()];
                    case 2: return [2 /*return*/, _a.sent()];
                    case 3: return [2 /*return*/, null];
                }
            });
        });
    }
    /**
     * 获取文件
     * @param path 文件路径
     * @param then then?
     * @param obj obj?
     * @returns 文件内容
     */
    function _getFile(path_1) {
        return __awaiter(this, arguments, void 0, function (path, then, obj) {
            var url;
            if (then === void 0) { then = null; }
            if (obj === void 0) { obj = null; }
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        url = '/api/file/getFile';
                        return [4 /*yield*/, _rqFORSiyuan(url, {
                                path: path
                            }).then(function (v) {
                                if (then)
                                    then(v, obj);
                            })];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    }
    /**
     * 写入文件
     * @param path 文件路径
     * @param filedata 文件数据
     * @param then then?
     * @param obj obj?
     * @param isDir 是否是路径
     * @param modTime 修改时间
     * @returns Promise\<void\>
    */
    function _writeFile(path_1, filedata_1) {
        return __awaiter(this, arguments, void 0, function (path, filedata, then, obj, isDir, modTime) {
            var blob, file, formdata;
            if (then === void 0) { then = null; }
            if (obj === void 0) { obj = null; }
            if (isDir === void 0) { isDir = false; }
            if (modTime === void 0) { modTime = Date.now(); }
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        blob = new Blob([filedata]);
                        file = new File([blob], path.split('/').pop());
                        formdata = new FormData();
                        formdata.append("path", path);
                        formdata.append("file", file);
                        formdata.append("isDir", isDir.toString());
                        formdata.append("modTime", modTime.toString());
                        return [4 /*yield*/, fetch("/api/file/putFile", {
                                body: formdata,
                                method: 'POST',
                                headers: {
                                    Authorization: "Token \"\""
                                }
                            }).then(function (v) {
                                if (then)
                                    then(obj);
                                return v;
                            })];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    }
    /**
     * 发送消息
     * @param type 消息类型 - "ok" or "error"
     * @param message 消息内容
     * @param time 持续时间
     * @returns Promise\<void\>
     */
    function _postMessage(type_1, message_1) {
        return __awaiter(this, arguments, void 0, function (type, message, time) {
            var url;
            if (time === void 0) { time = null; }
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (type == "ok")
                            url = "/api/notification/pushMsg";
                        else if (type == "error")
                            url = "api/notification/pushErrMsg";
                        if (!time) return [3 /*break*/, 2];
                        return [4 /*yield*/, _rqFORSiyuan(url, { "msg": message, "timeout": time })];
                    case 1:
                        _a.sent();
                        return [3 /*break*/, 4];
                    case 2: return [4 /*yield*/, _rqFORSiyuan(url, { "msg": message })];
                    case 3:
                        _a.sent();
                        _a.label = 4;
                    case 4: return [2 /*return*/];
                }
            });
        });
    }

    /**
     * 加载全局变量
     */
    function loadGlobalVars() {
        return __awaiter(this, void 0, void 0, function () {
            var currentLang;
            return __generator(this, function (_a) {
                /**
                 * ! 默认配置文件
                 */
                globalThis.defaultConf = {
                    "version": 11,
                    "theme": {
                        "codeBlock": true,
                        "reference": true,
                        "bazaar": true,
                        "embeddedBlock": true,
                        "title": true,
                        "titleShadow": true,
                        "titleIcon": true,
                        "database": true,
                        "doctree": true,
                        "mark": true
                    },
                    "plugins": {
                        "shortcutPanel": true,
                        "mathPanel": false,
                        "backgroundCoverDesktop": true,
                        "backgroundCoverMobile": false,
                        "doubleTabbar": false
                    }
                };
                /**
                 * ! 默认消息本地化
                 */
                globalThis.localMessage = {
                    "language": {
                        "zh_CN": true,
                        "en_US": true
                    },
                    "loadCssFail": {
                        "zh_CN": "加载主题VSCode Lite Edit失败，无法获取当前样式表",
                        "en_US": "Load theme VSCode Lite Edit failed, can't load current style table"
                    },
                    "loadFinish": {
                        "zh_CN": "主题VSCode Lite Edit加载完成",
                        "en_US": "Theme VSCode Lite Edit load finished"
                    },
                    "confUpdate": {
                        "zh_CN": "VSCE:主题配置文件需要更新，请点击<code>VC</code>按钮重新保存配置文件",
                        "en_US": "VSCE:Theme conf file needs update, please click <code>VC</code> button to save the configuration file again"
                    },
                    "confNotSave": {
                        "zh_CN": "VSCE:配置未保存",
                        "en_US": "VSCE:Configurations not saved"
                    },
                    "confSave": {
                        "zh_CN": "VSCE:配置保存成功，稍后自动刷新",
                        "en_US": "VSCE:Configuration save successed, auto reload later"
                    },
                    "label-aria": {
                        "zh_CN": "VSCode Lite 主题设置",
                        "en_US": "VSCode Lite theme setting"
                    },
                    "settingPanelTitle": {
                        "zh_CN": 'VSCode Lite Edit设置',
                        "en_US": "VSCode Lite Edit Settings"
                    },
                    "saveReload": {
                        "zh_CN": '保存并刷新',
                        "en_US": 'Save and Reload'
                    },
                    "nSave": {
                        "zh_CN": '不保存',
                        "en_US": "NOT Save"
                    },
                    "oReload": {
                        "zh_CN": '刷新思源界面',
                        "en_US": 'Reload Siyuan'
                    },
                    "tip1": {
                        "zh_CN": "直接关闭不保存哦，必须点击保存按钮",
                        "en_US": "Close it directly without saving, you must click the Save button"
                    },
                    "tip2": {
                        "zh_CN": "刷新可能无效，重启思源即可生效",
                        "en_US": "Reload may useless, you can restart Siyuan to enable the changes"
                    },
                    "tip3": {
                        "zh_CN": "点击一行中任意位置",
                        "en_US": "Click anywhere in a row"
                    },
                    "cbitem": {
                        "zh_CN": '代码块样式',
                        "en_US": "code block style"
                    },
                    "refitem": {
                        "zh_CN": '引用标签样式',
                        "en_US": 'reference label style'
                    },
                    "bazitem": {
                        "zh_CN": '集市样式',
                        "en_US": "bazaar style"
                    },
                    "emitem": {
                        "zh_CN": '嵌入块样式',
                        "en_US": "embedded block style"
                    },
                    "emdesc": {
                        "zh_CN": "限制嵌入块高度",
                        "en_US": "Limit the height of embedded block"
                    },
                    "tititem": {
                        "zh_CN": '标题块样式',
                        "en_US": "Heading block style"
                    },
                    "titleShadow": {
                        "zh_CN": "标题添加阴影",
                        "en_US": "Heading add shadow"
                    },
                    "titleShadowDesc": {
                        "zh_CN": "仅启用标题样式有效",
                        "en_US": "Only effective when enable heading style"
                    },
                    "titleIcon": {
                        "zh_CN": "标题前添加图标",
                        "en_US": "Add icon before title"
                    },
                    "dbitem": {
                        "zh_CN": '数据库样式',
                        "en_US": 'database style'
                    },
                    "markitem": {
                        "zh_CN": "高亮标注样式",
                        "en_US": "highlight mark style"
                    },
                    "scitem": {
                        "zh_CN": '（插件）快捷键面板样式',
                        "en_US": '(plugin) Shortcut key panel style'
                    },
                    "ftitem": {
                        "zh_CN": "文档树和大纲样式",
                        "en_US": 'Doc tree and Outline style'
                    },
                    "bgdesktop": {
                        "zh_CN": "（插件）在电脑端启用“替换背景图片”插件",
                        "en_US": "(plguin) Enable plugin \"Background cover adaption\" on desktop"
                    },
                    "bgdesc": {
                        "zh_CN": "需要打开“替换背景图片”插件设置将“前景透明”调到0哦!建议启用插件的“背景虚化”功能!",
                        "en_US": "You need to open the setting of \"Background Cover\" plugin and set the \"Opacity of foreground\" to 0!Suggest turn on the \"Blurring\" setting of the plugin!"
                    },
                    "bgmobile": {
                        "zh_CN": "（插件）在移动端启用“替换背景图片”插件",
                        "en_US": "(plugin) Enable plguin \"Background cover adaption\" on mobile"
                    },
                    "mathitem": {
                        "zh_CN": "（插件）数学增强插件调整",
                        "en_US": "(plugin) math enhance plugin adjustion"
                    },
                    "mathdesc": {
                        "zh_CN": "无法显示水平滚动条",
                        "en_US": "Can't show horizon scroll bar"
                    },
                    "doubleTabbaritem": {
                        "zh_CN": "（实验性）启用双标签栏",
                        "en_US": "(Expermental) Enable double tab bar"
                    },
                    "doubleTabbardesc": {
                        "zh_CN": "将钉住的标签移动到新标签栏（有缺陷！）",
                        "en_US": "Move pinned tab to new tab bar(WITH BUGS!)"
                    },
                    "doubleTabbarMessage": {
                        "zh_CN": "VSCE:点击暂时不能改变标签页，请手动点击原标签页",
                        "en_US": "VSCE:Can't change tab while clicking now, click original tab manually please"
                    }
                };
                currentLang = document.documentElement.lang;
                if (localMessage["language"][currentLang] != undefined) {
                    // @ts-ignore
                    globalThis.defLag = currentLang;
                }
                else {
                    globalThis.defLag = "en_US";
                }
                // ! 所有用到的计时器
                globalThis.vscTimer = {
                    // 背景插件加载后可能禁用，使用计时器定时刷新背景插件状态
                    bgTimer: null,
                    // 背景插件属性修改的监听器，用来监测背景状态变化
                    bgObserTimer: null
                };
                // ! 所有用到的监听器
                globalThis.vscObserver = {
                    // 背景插件观察器
                    bgObserver: null,
                    // 标签栏状态观察器
                    tabbarObserver: null,
                };
                return [2 /*return*/];
            });
        });
    }

    function bg(times) {
        // 背景自定义插件，部分情况下插件加载缓慢可重复检测一次
        var bglayer = document.getElementById("bglayer");
        if (bglayer) {
            var style = window.getComputedStyle(bglayer);
            var body = document.body;
            if (style.getPropertyValue("display") != 'none') {
                body.classList.add('bgenable');
            }
            else if (style.getPropertyValue("display") == 'none') {
                // console.log("disable background");
                body.classList.remove('bgenable');
            }
            // 刚开始每2秒重新检测状态，检测10秒
            if (times < 5) {
                globalThis.vscTimer.bgTimer = setTimeout(bg, 2000, times + 1);
            }
            else {
                globalThis.vscTimer.bgTimer = null;
            }
        }
        else if (times == 0 || times == 1) {
            // 未启用插件3秒后重新检测两遍
            setTimeout(bg, 3000, times + 1);
        }
    }
    // 监听背景自定义插件的属性修改
    function bgobserver(times) {
        var bglayer = document.getElementById("bglayer");
        if (bglayer) {
            globalThis.vscObserver.bgObserver = new MutationObserver(function (mutationsList) {
                for (var _i = 0, mutationsList_1 = mutationsList; _i < mutationsList_1.length; _i++) {
                    var mutation = mutationsList_1[_i];
                    if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
                        // 样式发生变化时执行的代码
                        bg(0);
                    }
                }
            });
            globalThis.vscObserver.bgObserver.observe(bglayer, {
                attributes: true, // 监听属性变化
                attributeFilter: ['style'] // 只监听 style 属性
            });
            globalThis.vscTimer.bgObserTimer = null;
        }
        else {
            // if (times == 0 && !document.body.classList.contains('vscmobile')) {
            if (times == 0) {
                // 运行失败等待5秒
                globalThis.vscTimer.bgObserTimer = setTimeout(bgobserver, 5000, 1);
            }
            else if (times == 1) {
                console.error("背景插件监听失败，修改插件启用状态需手动刷新");
                globalThis.vscTimer.bgObserTimer = null;
            }
        }
    }

    // 添加tabbar的观察器，不要再失效了
    function addTabbarObserver(tabbar) {
        if (globalThis.vscObserver.tabbarObserver == null) {
            // 先调用一次调节函数
            changeTabbar(tabbar);
            // 定义观察器
            globalThis.vscObserver.tabbarObserver = new MutationObserver(function (mutationsList) {
                for (var _i = 0, mutationsList_1 = mutationsList; _i < mutationsList_1.length; _i++) {
                    var mutation = mutationsList_1[_i];
                    if (mutation.type == 'childList' || mutation.type == 'attributes') {
                        console.log("调节tab宽度");
                        changeTabbar(tabbar);
                    }
                }
            });
            // 绑定观察器
            globalThis.vscObserver.tabbarObserver.observe(tabbar, {
                childList: true,
                subtree: true,
                attributes: true,
                attributeFilter: ["class"]
            });
        }
    }
    // 调节tab宽度用
    function changeTabbar(tabbar) {
        var itemList = tabbar.querySelectorAll(".item");
        var pinList = tabbar.querySelectorAll(".item--pin");
        var width = 0;
        // 去掉右侧宽度
        Array.from(itemList).forEach(function (item) {
            item.style.removeProperty("margin-right");
        });
        // 计算所有钉住页签的宽度
        Array.from(pinList).forEach(function (item) {
            width += item.getBoundingClientRect().width;
        });
        // 设置钉住页签右侧宽度
        if (width <= document.querySelector(".layout__center").getBoundingClientRect().width && width > 0) {
            pinList[pinList.length - 1].style.marginRight = "calc(100% - ".concat(width, "px)");
        }
    }

    /**
     * 具体设置项映射，由设置面板中的id映射到配置文件中
     * 设置面板配置项id：配置项范围，配置项键名
     */
    var settingKeyMap = {
        codeBlock: { section: 'theme', key: 'codeBlock' }, // 代码块样式
        referenceBlock: { section: 'theme', key: 'reference' }, // 引用块样式
        bazaarStyle: { section: 'theme', key: 'bazaar' }, // 集市样式
        titleBlock: { section: 'theme', key: 'title' }, // 标题块样式
        embeddedBlock: { section: "theme", key: 'embeddedBlock' }, // 嵌入块样式
        titleShadow: { section: 'theme', key: 'titleShadow' }, // 标题阴影
        titleIcon: { section: 'theme', key: 'titleIcon' }, // 标题图标
        database: { section: 'theme', key: 'database' }, // 数据库
        doctree: { section: 'theme', key: 'doctree' }, // 文档树
        mark: { section: 'theme', key: 'mark' }, // 标记
        scPanelStyle: { section: 'plugins', key: 'shortcutPanel' }, // 快捷键面板
        mathPanel: { section: 'plugins', key: 'mathPanel' }, // 数学面板
        backgroundCoverDesktop: { section: 'plugins', key: 'backgroundCoverDesktop' }, // 桌面端图片背景
        backgroundCoverMobile: { section: 'plugins', key: 'backgroundCoverMobile' }, // 移动端图片背景
        doubleTabbar: { section: 'plugins', key: 'doubleTabbar' }, // 双标签栏
    };

    /**
     * 创建一个包含标签和复选框的 HTML 结构
     */
    function createSettingsWindow() {
        return __awaiter(this, void 0, void 0, function () {
            function closeAndSave() {
                return __awaiter(this, void 0, void 0, function () {
                    var saveSt, ckb;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                saveSt = defaultConf;
                                ckb = document.getElementsByClassName("vslite_sets");
                                Array.from(ckb).forEach(function (checkbox) {
                                    var id = checkbox.id;
                                    var ck = checkbox.checked;
                                    // ! 保存设置到json
                                    var mapping = settingKeyMap[id];
                                    if (mapping) {
                                        saveSt[mapping.section][mapping.key] = ck;
                                    }
                                });
                                // 修改配置文件版本
                                saveSt["version"] = defaultConf["version"];
                                return [4 /*yield*/, putSettings(saveSt)];
                            case 1:
                                _a.sent();
                                _postMessage("ok", localMessage["confSave"][defLag]);
                                setTimeout(function () { window.location.reload(); }, 200);
                                document.body.removeChild(dialogSetting);
                                return [2 /*return*/];
                        }
                    });
                });
            }
            function closeNotSave() {
                _postMessage("error", localMessage["confNotSave"][defLag], 3000);
                document.body.removeChild(dialogSetting);
            }
            var dialogSetting, dialog, scrim, dialogContainer, dialogBody, title, settings, saveButton, notSaveButton, refreshButton, label1, label2, label3, space, div1, div2, div3;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        dialogSetting = document.createElement('div');
                        dialogSetting.setAttribute("data-key", "dialog-setting");
                        dialogSetting.className = "b3-dialog--open";
                        document.body.appendChild(dialogSetting);
                        dialog = document.createElement('div');
                        dialog.className = "b3-dialog";
                        dialog.style.zIndex = '14';
                        dialogSetting.appendChild(dialog);
                        scrim = document.createElement('div');
                        scrim.className = "b3-dialog__scrim";
                        scrim.onclick = function () {
                            closeNotSave();
                        };
                        dialog.appendChild(scrim);
                        dialogContainer = document.createElement('div');
                        dialogContainer.className = "b3-dialog__container";
                        if (document.body.classList.contains('vscmobile')) {
                            dialogContainer.style.width = '90vw';
                        }
                        else {
                            dialogContainer.style.width = '60vw';
                        }
                        dialogContainer.style.height = '80vh';
                        dialog.appendChild(dialogContainer);
                        dialogBody = document.createElement('div');
                        dialogBody.className = 'b3-dialog__body';
                        dialogBody.setAttribute("vslite", "SettingPanel");
                        dialogContainer.appendChild(dialogBody);
                        title = document.createElement('h2');
                        title.textContent = localMessage["settingPanelTitle"][defLag];
                        title.setAttribute("data-subtype", "h2");
                        // title.setAttribute("data-type", "NodeHeading");
                        title.className = "h2";
                        dialogBody.appendChild(title);
                        return [4 /*yield*/, fetchSettingsArray()];
                    case 1:
                        settings = _a.sent();
                        // 遍历数组添加选项，创建标签和复选框
                        settings.forEach(function (setting) {
                            var label;
                            if (setting === null || setting === void 0 ? void 0 : setting.description) {
                                label = document.createElement('div');
                            }
                            else {
                                label = document.createElement('span');
                            }
                            label.textContent = setting.label;
                            label.setAttribute("for", setting.id);
                            label.className = "fn__flex-1";
                            if (setting === null || setting === void 0 ? void 0 : setting.description) {
                                var description = document.createElement('div');
                                description.textContent = setting.description;
                                description.setAttribute("for", setting.id);
                                description.className = "b3-label__text";
                                label.appendChild(description);
                            }
                            var space = document.createElement('span');
                            space.className = 'fn__space';
                            var checkbox = document.createElement('input');
                            checkbox.type = 'checkbox';
                            checkbox.id = setting.id;
                            checkbox.checked = setting.enable;
                            checkbox.className = "b3-switch fn__flex-center vslite_sets";
                            var div = document.createElement('label');
                            div.className = "fn__flex b3-label";
                            div.appendChild(label);
                            div.appendChild(space);
                            div.appendChild(checkbox);
                            dialogBody.appendChild(div);
                        });
                        saveButton = document.createElement('button');
                        saveButton.textContent = localMessage["saveReload"][defLag];
                        saveButton.className = "b3-button b3-button--outline fn__flex-center fn__size200";
                        saveButton.onclick = function () {
                            closeAndSave();
                        };
                        notSaveButton = document.createElement('button');
                        notSaveButton.textContent = localMessage["nSave"][defLag];
                        notSaveButton.className = "b3-button b3-button--outline fn__flex-center fn__size200";
                        notSaveButton.onclick = function () {
                            closeNotSave();
                        };
                        refreshButton = document.createElement('button');
                        refreshButton.textContent = localMessage['oReload'][defLag];
                        refreshButton.className = "b3-button b3-button--outline fn__flex-center fn__size200";
                        refreshButton.onclick = function () {
                            window.location.reload();
                        };
                        label1 = document.createElement('span');
                        label1.textContent = localMessage["tip1"][defLag];
                        label1.className = "fn__flex-1 fn__flex-center";
                        label2 = document.createElement('span');
                        label2.textContent = localMessage["tip2"][defLag];
                        label2.className = "fn__flex-1 fn__flex-center";
                        label3 = document.createElement('span');
                        label3.textContent = localMessage["tip3"][defLag];
                        label3.className = "fn__flex-1 fn__flex-center";
                        space = document.createElement('span');
                        space.className = 'fn__space';
                        div1 = document.createElement('label');
                        div1.className = "fn__flex b3-label";
                        div1.appendChild(label1);
                        div1.appendChild(space.cloneNode(true));
                        div1.appendChild(saveButton);
                        dialogBody.appendChild(div1);
                        div2 = document.createElement('label');
                        div2.className = "fn__flex b3-label";
                        div2.appendChild(label2);
                        div2.appendChild(space.cloneNode(true));
                        div2.appendChild(notSaveButton);
                        dialogBody.appendChild(div2);
                        div3 = document.createElement('label');
                        div3.className = "fn__flex b3-label";
                        div3.appendChild(label3);
                        div3.appendChild(space.cloneNode(true));
                        div3.appendChild(refreshButton);
                        dialogBody.appendChild(div3);
                        return [2 /*return*/];
                }
            });
        });
    }
    /**
     * NOTE 获取设置文件数组
     * @returns Promise\<SettingItem[]\>
     */
    function fetchSettingsArray() {
        return __awaiter(this, void 0, void 0, function () {
            var re;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, _getFile("/data/snippets/vsc_edit.config.json", function (v) { return __awaiter(_this, void 0, void 0, function () {
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0:
                                        if (v == null) {
                                            v = defaultConf;
                                        }
                                        return [4 /*yield*/, getSettingArrays(v)];
                                    case 1:
                                        re = _a.sent();
                                        return [2 /*return*/];
                                }
                            });
                        }); })];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, re];
                }
            });
        });
    }
    /**
     * NOTE 向设置面板中添加设置项（数组）
     * @param v ThemeConfig
     * @returns Promise\<SettingItem[]\>
     */
    function getSettingArrays(v) {
        return __awaiter(this, void 0, void 0, function () {
            var settings;
            var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5;
            return __generator(this, function (_6) {
                settings = [];
                // ! 设置页添加设置选项
                // 标题
                settings.push({ label: localMessage["tititem"][defLag], id: 'titleBlock', enable: (_b = (_a = v === null || v === void 0 ? void 0 : v.theme) === null || _a === void 0 ? void 0 : _a.title) !== null && _b !== void 0 ? _b : false });
                // 标题阴影
                settings.push({ label: localMessage["titleShadow"][defLag], description: localMessage["titleShadowDesc"][defLag], id: 'titleShadow', enable: (_d = (_c = v === null || v === void 0 ? void 0 : v.theme) === null || _c === void 0 ? void 0 : _c.titleShadow) !== null && _d !== void 0 ? _d : false });
                // 标题图标
                settings.push({ label: localMessage["titleIcon"][defLag], description: localMessage["titleShadowDesc"][defLag], id: 'titleIcon', enable: (_f = (_e = v === null || v === void 0 ? void 0 : v.theme) === null || _e === void 0 ? void 0 : _e.titleIcon) !== null && _f !== void 0 ? _f : false });
                // 文档树和大纲
                settings.push({ label: localMessage["ftitem"][defLag], id: 'doctree', enable: (_h = (_g = v === null || v === void 0 ? void 0 : v.theme) === null || _g === void 0 ? void 0 : _g.doctree) !== null && _h !== void 0 ? _h : false });
                // 代码块
                settings.push({ label: localMessage["cbitem"][defLag], id: 'codeBlock', enable: (_k = (_j = v === null || v === void 0 ? void 0 : v.theme) === null || _j === void 0 ? void 0 : _j.codeBlock) !== null && _k !== void 0 ? _k : false });
                // 引用
                settings.push({ label: localMessage["refitem"][defLag], id: 'referenceBlock', enable: (_m = (_l = v === null || v === void 0 ? void 0 : v.theme) === null || _l === void 0 ? void 0 : _l.reference) !== null && _m !== void 0 ? _m : false });
                // 标记
                settings.push({ label: localMessage["markitem"][defLag], id: 'mark', enable: (_p = (_o = v === null || v === void 0 ? void 0 : v.theme) === null || _o === void 0 ? void 0 : _o.mark) !== null && _p !== void 0 ? _p : false });
                // 集市
                settings.push({ label: localMessage["bazitem"][defLag], id: 'bazaarStyle', enable: (_r = (_q = v === null || v === void 0 ? void 0 : v.theme) === null || _q === void 0 ? void 0 : _q.bazaar) !== null && _r !== void 0 ? _r : false });
                // 嵌入块
                settings.push({ label: localMessage["emitem"][defLag], description: localMessage["emdesc"][defLag], id: 'embeddedBlock', enable: (_t = (_s = v === null || v === void 0 ? void 0 : v.theme) === null || _s === void 0 ? void 0 : _s.embeddedBlock) !== null && _t !== void 0 ? _t : false });
                // 数据库
                settings.push({ label: localMessage["dbitem"][defLag], id: 'database', enable: (_v = (_u = v === null || v === void 0 ? void 0 : v.theme) === null || _u === void 0 ? void 0 : _u.database) !== null && _v !== void 0 ? _v : false });
                // 快捷键面板
                settings.push({ label: localMessage["scitem"][defLag], id: 'scPanelStyle', enable: (_x = (_w = v === null || v === void 0 ? void 0 : v.plugins) === null || _w === void 0 ? void 0 : _w.shortcutPanel) !== null && _x !== void 0 ? _x : false });
                // 替换背景图片插件电脑端
                settings.push({ label: localMessage["bgdesktop"][defLag], description: localMessage["bgdesc"][defLag], id: 'backgroundCoverDesktop', enable: (_z = (_y = v === null || v === void 0 ? void 0 : v.plugins) === null || _y === void 0 ? void 0 : _y.backgroundCoverDesktop) !== null && _z !== void 0 ? _z : false });
                // 替换背景图片插件移动端
                settings.push({ label: localMessage["bgmobile"][defLag], description: localMessage["bgdesc"][defLag], id: 'backgroundCoverMobile', enable: (_1 = (_0 = v === null || v === void 0 ? void 0 : v.plugins) === null || _0 === void 0 ? void 0 : _0.backgroundCoverMobile) !== null && _1 !== void 0 ? _1 : false });
                // 数学公式增强插件
                settings.push({ label: localMessage["mathitem"][defLag], description: localMessage["mathdesc"][defLag], id: 'mathPanel', enable: (_3 = (_2 = v === null || v === void 0 ? void 0 : v.plugins) === null || _2 === void 0 ? void 0 : _2.mathPanel) !== null && _3 !== void 0 ? _3 : false });
                // 双标签栏
                settings.push({ label: localMessage["doubleTabbaritem"][defLag], description: localMessage["doubleTabbardesc"][defLag], id: 'doubleTabbar', enable: (_5 = (_4 = v === null || v === void 0 ? void 0 : v.plugins) === null || _4 === void 0 ? void 0 : _4.doubleTabbar) !== null && _5 !== void 0 ? _5 : false });
                return [2 /*return*/, settings];
            });
        });
    }
    /**
     * ! 获取设置
     * @returns Promise\<EnableSettings[]\>
     */
    function getSettings() {
        return __awaiter(this, void 0, void 0, function () {
            var str;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: 
                    // var res = _analyseResponse(_getFile("/data/snippets/vsc_edit.config.json"));
                    return [4 /*yield*/, _getFile("/data/snippets/vsc_edit.config.json", function (v) { return __awaiter(_this, void 0, void 0, function () {
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0:
                                        if (v == null) {
                                            v = globalThis.defaultConf;
                                            putSettings(v);
                                        }
                                        return [4 /*yield*/, showElementSettings(v)];
                                    case 1:
                                        str = _a.sent();
                                        return [2 /*return*/];
                                }
                            });
                        }); })];
                    case 1:
                        // var res = _analyseResponse(_getFile("/data/snippets/vsc_edit.config.json"));
                        _a.sent();
                        return [2 /*return*/, str];
                }
            });
        });
    }
    /**
     * ! 保存设置
     * @param settings
     * @returns Promise\<void\>
     */
    function putSettings(settings) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (settings == null) {
                            return [2 /*return*/];
                        }
                        return [4 /*yield*/, _writeFile("/data/snippets/vsc_edit.config.json", JSON.stringify(settings), null, null, false, Date.now())];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    }
    /**
     * ! 获取当前启用的设置并返回对应的列表
     * @param settings
     * @returns Promise\<EnableSettings[]\>
     */
    function showElementSettings(settings) {
        return __awaiter(this, void 0, void 0, function () {
            var lab;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        lab = [];
                        if (!(settings["version"] < defaultConf["version"] || settings["version"] == undefined)) return [3 /*break*/, 2];
                        // console.log(settings["version"]);
                        return [4 /*yield*/, _postMessage("ok", localMessage["confUpdate"][defLag])];
                    case 1:
                        // console.log(settings["version"]);
                        _a.sent();
                        _a.label = 2;
                    case 2:
                        // ! 从设置中获取启用的设置项
                        // 主题设置项
                        Object.entries(settings.theme).forEach(function (_a) {
                            var key = _a[0], enabled = _a[1];
                            if (enabled)
                                lab.push(key);
                        });
                        // 插件设置项
                        Object.entries(settings.plugins).forEach(function (_a) {
                            var key = _a[0], enabled = _a[1];
                            if (enabled)
                                lab.push(key);
                        });
                        return [2 /*return*/, lab];
                }
            });
        });
    }

    // 主题默认加载时进行的行为
    // ! js代码加载后立即执行
    (function () {
        return __awaiter(this, void 0, void 0, function () {
            var cssTable, labels;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        cssTable = document.getElementById('themeStyle');
                        // 添加全局变量
                        return [4 /*yield*/, loadGlobalVars()];
                    case 1:
                        // 添加全局变量
                        _a.sent();
                        if (!cssTable) return [3 /*break*/, 4];
                        return [4 /*yield*/, getSettings()];
                    case 2:
                        labels = _a.sent();
                        // 添加主题菜单
                        addThemeToolBar();
                        // 向css中插入语句
                        addImports(cssTable, labels);
                        // 移除CSS规则
                        removeCSSRules(cssTable);
                        // 添加固定属性
                        addFixedAttribute(labels);
                        // 修复导出pdf没有样式的问题
                        return [4 /*yield*/, addPdfStyle(labels)];
                    case 3:
                        // 修复导出pdf没有样式的问题
                        _a.sent();
                        // 加载完成(o゜▽゜)o☆
                        console.log(localMessage["loadFinish"][defLag]);
                        return [3 /*break*/, 6];
                    case 4: 
                    // 加载失败
                    return [4 /*yield*/, _postMessage('error', globalThis.localMessage["localCssFail"][globalThis.defLag])];
                    case 5:
                        // 加载失败
                        _a.sent();
                        _a.label = 6;
                    case 6: return [2 /*return*/];
                }
            });
        });
    })();
    // ! 更换主题时移除修改内容
    window.destroyTheme = function () { return __awaiter(void 0, void 0, void 0, function () {
        var key;
        return __generator(this, function (_a) {
            // 移除主题按钮
            document.querySelector("#vscleToolbar").remove();
            // 移除body特殊适配语句
            document.body.classList.remove('bgenable');
            // 移除双标签栏的style
            Array.from(document.querySelector(".layout__center").querySelectorAll(".item--pin")).forEach(function (item) {
                item.style.removeProperty("margin-right");
                if (item.style.length == 0)
                    item.removeAttribute("style");
            });
            // 移除计时器
            for (key in globalThis.timer) {
                if (globalThis.timer[key] != null) {
                    // console.log("remove timer");
                    clearTimeout(globalThis.timer[key]);
                    clearInterval(globalThis.timer[key]);
                    globalThis.timer[key] = null;
                }
            }
            // 移除监视器
            for (key in globalThis.observer) {
                if (globalThis.observer[key] != null) {
                    // console.log("remove observer");
                    globalThis.observer[key].disconnect();
                    globalThis.observer[key] = null;
                }
            }
            // 删除全局变量
            delete globalThis.defaultConf;
            delete globalThis.localMessage;
            delete globalThis.defLag;
            delete globalThis.timer;
            delete globalThis.observer;
            return [2 /*return*/];
        });
    }); };
    /**
     * 创建工具栏的按钮
     */
    function addThemeToolBar() {
        var vscToolBar = document.getElementById("vscleToolbar");
        if (vscToolBar == null) {
            var toolbarVIP = document.getElementById("toolbarVIP");
            var windowControls = document.getElementById("windowControls");
            vscToolBar = document.createElement("div");
            vscToolBar.id = "vscleToolbar";
            vscToolBar.setAttribute("aria-label", localMessage["label-aria"][defLag]);
            if (toolbarVIP == null) {
                try {
                    vscToolBar.className = "toolbar__item ariaLabel";
                    vscToolBar.style.height = "23.5px";
                    windowControls.parentElement.insertBefore(vscToolBar, windowControls);
                }
                catch (error) {
                    document.body.classList.add("vscmobile");
                    vscToolBar.className = "block__icon fn__flex-center ariaLabel";
                    vscToolBar.style.height = "14px";
                    var breadcrumbButtons = document.getElementsByClassName("block__icon fn__flex-center ariaLabel");
                    try {
                        var firstButton = breadcrumbButtons[0];
                        if (firstButton) {
                            firstButton.parentElement.insertBefore(vscToolBar, firstButton);
                        }
                        else {
                            throw new Error("Can't find first button in breadcrumb.");
                        }
                    }
                    catch (_a) {
                        setTimeout(function () {
                            var firstButton = breadcrumbButtons[0];
                            if (firstButton) {
                                firstButton.parentElement.insertBefore(vscToolBar, firstButton);
                            }
                        }, 1000);
                    }
                }
            }
            else {
                vscToolBar.className = "toolbar__item ariaLabel";
                vscToolBar.style.height = "23.5px";
                toolbarVIP.parentElement.insertBefore(vscToolBar, toolbarVIP);
            }
        }
        vscToolBar.innerHTML = "VC";
        // vscToolBar.innerHTML = "<img src=\"resources\\h6.bmp\"\\>";
        vscToolBar.addEventListener("click", function () {
            // 调用函数创建设置窗口
            createSettingsWindow();
        });
    }
    /**
     * 向css表中插入引用的语句
     * @param table \<link css\>
     * @param labels EnableSettings[]
     */
    function addImports(table, labels) {
        var sheet = table.sheet;
        var i = 0;
        // ! 向css表中插入引用的语句
        labels.forEach(function (it) {
            switch (it) {
                case "codeBlock":
                    sheet.insertRule('@import url(sub/block/codeBlock.css);', 4 + i);
                    i += 1;
                    break;
                case "reference":
                    sheet.insertRule('@import url(sub/block/reference.css);', 4 + i);
                    i += 1;
                    break;
                case "bazaar":
                    sheet.insertRule('@import url(sub/app/bazaar.css);', 4 + i);
                    i += 1;
                    break;
                case "embeddedBlock":
                    sheet.insertRule('@import url(sub/block/embeddedBlock.css);', 4 + i);
                    i += 1;
                    break;
                case "title":
                    sheet.insertRule('@import url(sub/block/title.css);', 4 + i);
                    i += 1;
                    break;
                case "titleShadow":
                    sheet.insertRule('@import url(sub/block/title-shadow.css);', 4 + i);
                    i += 1;
                    break;
                case "titleIcon":
                    sheet.insertRule('@import url(sub/block/title-icon.css);', 4 + i);
                    i += 1;
                    break;
                case "shortcutPanel":
                    sheet.insertRule('@import url(sub/plugin/keymapPlugin.css);', 4 + i);
                    i += 1;
                    break;
                case "database":
                    sheet.insertRule('@import url(sub/block/database.css);', 4 + i);
                    i += 1;
                    break;
                case "doctree":
                    sheet.insertRule('@import url(sub/app/filetree.css);', 4 + i);
                    i += 1;
                    break;
                case "backgroundCoverDesktop":
                case "backgroundCoverMobile":
                    if (!sheet.cssRules.toString().includes('backgroundPlugin.css')) {
                        sheet.insertRule('@import url(sub/plugin/backgroundPlugin.css);', 4 + i);
                        i += 1;
                    }
                    break;
                case "mathPanel":
                    if (!document.body.classList.contains('vscmobile')) {
                        sheet.insertRule('@import url(sub/plugin/mathEnhance.css);', 4 + i);
                        i += 1;
                    }
                    break;
                case "mark":
                    sheet.insertRule('@import url(sub/block/mark.css);', 4 + i);
                    i += 1;
                    break;
                case "doubleTabbar":
                    sheet.insertRule("@import url(sub/plugin/doubleTabbar.css);", 4 + i);
                    i += 1;
                    break;
            }
        });
    }
    /**
     * ! 添加固定属性
     * @param settings EnableSettings[]
     */
    function addFixedAttribute(settings) {
        // 运行
        // >>>>>>>>>>>>>>>>>>>>>>>>>>>>
        // 如果设置启用背景插件才进入判断
        if (settings.includes("backgroundCoverDesktop") && !document.body.classList.contains('vscmobile') || settings.includes("backgroundCoverMobile") && document.body.classList.contains('vscmobile')) {
            // 首先调用插件状态检测
            bg(0);
            // 添加观察器
            if (globalThis.vscObserver.bgObserver == null) {
                bgobserver(0);
            }
        }
        // 如果启用了双标签栏
        if (settings.includes("doubleTabbar") && !document.body.classList.contains("vscmobile")) {
            // 添加观察器
            if (globalThis.vscObserver.tabbarObserver == null) {
                addTabbarObserver(document.querySelector(".layout__center").querySelector(".layout-tab-bar"));
            }
        }
        // <<<<<<<<<<<<<<<<<<<<<<<<<<<<
    }
    /**
     * ! 添加导出pdf时候的样式
     * @param lab EnableSettings[]
     */
    function addPdfStyle(lab) {
        return __awaiter(this, void 0, void 0, function () {
            var list, str;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        list = [];
                        list.push("@charset \"UTF-8\";");
                        lab.forEach(function (it) {
                            switch (it) {
                                case "codeBlock":
                                    list.push('@import url(block/codeBlock.css);');
                                    break;
                                case "reference":
                                    list.push('@import url(block/reference.css);');
                                    break;
                                case "title":
                                    list.push('@import url(block/title.css);');
                                    break;
                                case "titleShadow":
                                    list.push('@import url(block/title-shadow.css);');
                                    break;
                                case "titleIcon":
                                    list.push('@import url(block/title-icon.css);');
                                    break;
                                case "database":
                                    list.push('@import url(block/database.css);');
                                    break;
                                case "mark":
                                    list.push('@import url(block/mark.css);');
                                    break;
                            }
                        });
                        str = list.join("\n");
                        return [4 /*yield*/, _writeFile("/conf/appearance/themes/siyuan-vscodelite-edit/sub/pdfPreview.css", str)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    }
    /**
     * 移除CSS规则，用于在可加载js的时候去掉PDF导出适配
     * @param table \<link css\>
     */
    function removeCSSRules(table) {
        var sheet = table.sheet;
        // 移除特定的 @import 规则
        var removeImportRule = function (sheet, url) {
            var rules = Array.from(sheet.cssRules);
            for (var i = 0; i < rules.length; i++) {
                var rule = rules[i];
                if (rule instanceof CSSImportRule && rule.href.includes(url)) {
                    sheet.deleteRule(i);
                    break; // 找到并删除目标规则后停止遍历
                }
            }
        };
        // 移除 @import("sub/pdfPreview.css") 规则
        removeImportRule(sheet, 'sub/pdfPreview.css');
    }

})();
